import {useState,useEffect} from 'react'
import {GetMenu,AddMenu, DelMenu,PutMenu} from '@/api/index'
import {Table,Button} from 'antd'
import EditMenu from './components/EditMenu'
import {useDispatch} from 'react-redux'
import {getPermission} from '../../../store/permissionSlice'

function MenuView() {
  const [isOpen,setIsOpen] = useState(false); //是否打开编辑弹框
  const [isAdd,setIsAdd] = useState(false); //是否添加
  const [menuList,setMenuList] = useState([]); //菜单列表
  const [menu,setMenu] = useState({})
  const dispatch = useDispatch();
  // 获取菜单方法
  function getMenu(){
    GetMenu({size:10000})
    .then(res=>{
      setMenuList(res.data.list)
      // 调用redux中getPermisison的异步方法，更新菜单
      dispatch(getPermission());
    })
  }

  // 组件挂载完毕获取菜单
  useEffect(()=>{
    getMenu();
  },[])
  function menuChange(e){
    if(isAdd){
      AddMenu(e)
      .then(res=>{
        if(res.data.code===0){
          alert("添加成功");
          getMenu();
        }
      })
    }else{
      PutMenu(e)
      .then(res=>{
        if(res.data.code===0){
          alert("修改成功");
          getMenu();
        }
      })
    }
    setIsOpen(false);
  }
  // 定义列
  const columns = [
    { title:"id", key:"id",dataIndex:"id"},
    {title:"菜单名",key:"name",dataIndex:"name"},
    {title:"路径",key:"path",dataIndex:"path"},
    {
      title:"操作",
      render:(row)=><div>
        <span onClick={()=>{
          setIsAdd(true);
          setIsOpen(true);
          setMenu({...row,fid:row.id})
        }}>添加</span>,
        <span onClick={()=>delMenu(row)}>
          删除
        </span>,
        <span onClick={()=>{
           setMenu({...row})
           setIsAdd(false);
           setIsOpen(true);
           
        }}>
          修改
        </span>
      </div>
    }
  ]
  function delMenu(row){
    DelMenu(row)
    .then(res=>{
      if(res.data.code===0){
        console.log("删除成功")
        getMenu();
      }
    })
  }
  return ( <div>
    <h3>菜单管理</h3>
    <Button type="primary" onClick={()=>{
      setIsAdd(true);
      setIsOpen(true);
      setMenu({fid:0})
    }}>添加</Button>
    <Table 
    columns={columns} 
    dataSource={menuList} 
    rowKey="id"
    pagination={{
      hideOnSinglePage:true
    }}
    />
    <EditMenu 
    isOpen={isOpen} 
    title="编辑/添加菜单"
    onCancel={()=>setIsOpen(false)}
    data={menu}
    onOk={e=>menuChange(e)}
     />
    </div> );
}

export default MenuView;